/**
 * 版权所有 2009-2015 旺晓杨 peonyxy@msn.cn
 **/
package com.cn;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ac.cintcm.sh.domain.AvgDosage;
import cn.ac.cintcm.sh.domain.Conversion;
import cn.ac.cintcm.sh.domain.Dosage;
import cn.ac.cintcm.sh.domain.FormatException;
import cn.ac.cintcm.sh.domain.Herb;
import cn.ac.cintcm.sh.domain.Prescription;
import cn.ac.cintcm.sh.domain.Unit;
import cn.ac.cintcm.sh.service.HerbService;
import cn.ac.cintcm.sh.service.PrescriptionService;
import cn.ac.cintcm.sh.service.TextService;

public class PrescriptionServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public PrescriptionServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		String doClass = request.getParameter("doClass");
		if(doClass != null && doClass.equals("namePres"))
		{
			this.namePres(request, response);
		}else if(doClass != null && doClass.equals("fjPre")){
			this.fjPre(request, response);
		}else if(doClass != null && doClass.equals("containPre")){
			this.containPre(request, response);
		}else if(doClass != null && doClass.equals("similarPrescription")){
			this.similarPrescription(request, response);
		}else if(doClass != null && doClass.equals("prescriptionsHer")){
			this.prescriptionsHer(request, response);
		}
		else if(doClass != null && doClass.equals("constructedPrescriptions")){
			this.constructedPrescriptions(request, response);
		}
		else if(doClass != null && doClass.equals("prBuildMost")){
			this.prBuildMost(request, response);
		}
		
		else if(doClass != null && doClass.equals("convert")){
			this.convert(request, response);
		}
		
		
	}

	/**
	 * 折量计算
	 * @param request
	 * @param response
	 */
	public void convert(HttpServletRequest request, HttpServletResponse response){
	
		String[] viewIds = request.getParameterValues("viewId");
		String fjId = request.getParameter("fjId");
		if(fjId == null || fjId.equals(""))
			return;
		StringBuffer str = new StringBuffer("");
		PrintWriter out = null;
		try {
				 
			 	out = response.getWriter();
				PrescriptionService prescriptionService = new PrescriptionService();
				Prescription prescription = prescriptionService.getPrescription(fjId);
				int size = viewIds.length;
				int[] viewId = new int[size];
				for(int i = 0 ; i<size ; i++){
					viewId[i] = Integer.parseInt(viewIds[i]);
				}
                HashMap<Integer, Conversion> convertedMap = 
                    prescriptionService.convert(Integer.parseInt(fjId), viewId).getConverted();
				
				if(prescription == null)
					return;
				
				Iterator iterator = prescription.getHerbs().iterator();
				Map map = getConvertedMap(convertedMap);
				str.append("{articles:[");
				if(iterator.hasNext()){
					Herb herb = (Herb) iterator.next();
					String dosage = "" ;
					if(herb.getDosage() != null){
						dosage = herb.getDosage().getQuantity()+herb.getDosage().getUnit();
					}
					str.append("{'herbName':'"+herb.getName()+"','dosage':'"+dosage+"'");
					this.addDosage(str, map, viewId, herb.getId());
					str.append("}");
				}
				while(iterator.hasNext()){
					Herb herb = (Herb) iterator.next();
					String dosage = "" ;
                    if(herb.getDosage() != null){
                        dosage = herb.getDosage().getQuantity()+herb.getDosage().getUnit();
                    }
					str.append(",{'herbName':'"+herb.getName()+"','dosage':'"+dosage+"'");
					this.addDosage(str, map, viewId, herb.getId());
					str.append("}");
				}
				str.append("]}");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("方剂折算剂量错误! >>"+this.getClass());
		}
	 out.print(str);
	 out.flush();
	}
	/**
	 *  设置观点对于中药剂量
	 * @param str
	 * @param map
	 * @param viewId
	 * @param herbId
	 */
	private void addDosage(StringBuffer str,Map map,int[] viewId,int herbId){
		int size = viewId.length;
		for(int i=0 ; i<size ;i++){
			String dosage = "" ;
			Unit o  = (Unit)map.get(viewId[i]+"*"+herbId);
	
			if(o != null){
				dosage = o.getQuantity()+o.getUnit();
			}
			str.append(",'id_"+viewId[i]+"_':'"+dosage+"'");

		}
		
	}
	/**
	 * 对观点-中药剂量折算重新组成
	 * key = 观点id+中药id
	 * value = 实际折算值
	 * @param convertedMap
	 * @return
	 */
	private Map  getConvertedMap(Map convertedMap){
		Map map = new HashMap();
		if(!convertedMap.isEmpty())
		{
			Iterator iterator = convertedMap.keySet().iterator();
			while(iterator.hasNext()){
				Integer viewId = (Integer)iterator.next();
				 Conversion conversion = (Conversion)convertedMap.get(viewId);
				 if(!conversion.getHerbsUnit().isEmpty()){
					 Iterator iteratorHer = conversion.getHerbsUnit().keySet().iterator();
					 while(iteratorHer.hasNext()){
						 Integer herbId = (Integer)iteratorHer.next();
						 map.put(viewId+"*"+herbId, conversion.getHerbsUnit().get(herbId));
						 
					 }
				 }
			}
		}
		return map;
	}
	/**
	 * 多方剂组成
	 * @param request
	 * @param response
	 */
	public void prBuildMost(HttpServletRequest request, HttpServletResponse response){
	
		String[] fjIds = request.getParameterValues("fjIds");
		if(fjIds == null)
			return;
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			try {
					PrescriptionService prescriptionService = new PrescriptionService();
//	
					Iterator iterator = prescriptionService.getAllPrescriptions(fjIds).iterator();
					str.append("{articles:[");
					if(iterator.hasNext())
					{
						Prescription prescription = (Prescription)iterator.next();
						str.append("{'id':"+prescription.getId()+",'name':'"+prescription.getName()+"',herb:'"+prescription.getText()+"'}");
				
						while(iterator.hasNext()){
							 prescription = (Prescription)iterator.next();
							 StringBuffer herbStr = new StringBuffer("");
							 Iterator iteratorHerb = prescription.getHerbs().iterator();
							 while(iteratorHerb.hasNext()){
								 Herb herb = (Herb)iteratorHerb.next();
								 herbStr.append(herb.getName()+" ");
							 }
							 
							str.append(",{'id':"+prescription.getId()+",'name':'"+prescription.getName()+"',herb:'"+prescription.getText()+"'}");
						}
					}
					str.append("]}");
					 out = response.getWriter();
				} catch (Exception e) {
					str.append("{'id':'-1','mes':'<font color=red>查询错误</font>'}");
				}
		 out.print(str);
		 out.flush();
	}
	
	/**
	 * 查询自拟
	 * @param request
	 * @param response
	 */
	public void constructedPrescriptions(HttpServletRequest request, HttpServletResponse response){
	
		String constructed = request.getParameter("constructed");
		if(constructed == null)
			return;
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			try {
					PrescriptionService prescriptionService = new PrescriptionService();
	
					Prescription prescription = prescriptionService.parsePrescription(constructed);
					if(prescription != null){
						if(prescription.getId() == -1)
							str.append("{id:-1,'mes':'未找到符合结果'}");
						else
							str.append("{id:'"+prescription.getId()+"'}");
					}
					else
						str.append("{id:-1,'mes':'未找到符合结果'}");
					 out = response.getWriter();
				} catch (Exception e) {
					str.append("{'id':'-1','mes':'<font color=red>查询错误</font>'}");
				}
		 out.print(str);
		 out.flush();
	}
	
	
	/**
	 * 取得包含1个或者多个中药的方剂
	 * @param request
	 * @param response
	 */
	public void prescriptionsHer(HttpServletRequest request, HttpServletResponse response){
		String herId = request.getParameter("herId");
		if(herId == null)
			return;
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			try {
				HerbService herbService = new HerbService();

				AvgDosage avg = herbService.getAvgDosage(herId);
                List<Dosage> dose = avg.getDosages();
				str.append("{articles:[");
				if(dose != null)
				{
                    for (Dosage d : dose) {
                        str.append("{'id':'1','name':'"+d.getName()+
                                "',dosage:" + d.getUnit().getQuantity()+
                                ",unit:'" + d.getUnit().getUnit() + "'},");
                    }
				}
                if (str.length() > "{articles:[".length()) {
                    str.deleteCharAt(str.length() - 1);
                }
				str.append("]}");
				 out = response.getWriter();
			
			} catch (Exception e) {
				str.append("{articles:[{'id':'','text':'<font color=red>������Ŵ���!</font>'}]}");
			}
		 out.print(str);
		 out.flush();
	}
	
	/****
	 * 获得相似组成方
	 * @param request
	 * @param response
	 */
	public void similarPrescription(HttpServletRequest request, HttpServletResponse response){
		String fjId = request.getParameter("fjId");
		if(fjId == null || (fjId = fjId.trim()).equals(""))
			return;
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			try {
				PrescriptionService prescriptionService = new PrescriptionService();

				Iterator iterator = prescriptionService.getSimilarPrescription(Integer.parseInt(fjId)).iterator();
				str.append("{articles:[");
				if(iterator.hasNext())
				{
					Prescription prescription = (Prescription)iterator.next();
					
					str.append("{'id':"+prescription.getId()+",'name':'"+prescription.getName()+"','herb':'"+prescription.getText()+"'}");
			
					while(iterator.hasNext()){
						 prescription = (Prescription)iterator.next();
						str.append(",{'id':"+prescription.getId()+",'name':'"+prescription.getName()+"','herb':'"+prescription.getText()+"'}");
					}
				}
				str.append("]}");
				 out = response.getWriter();
			} catch (Exception e) {
				str.append("{articles:[{'id':'','text':'<font color=red>������Ŵ���!</font>'}]}");
			}
		 out.print(str);
		 out.flush();
	}

	/**
	 * �����Ʋ�fafang 方剂按名称查询����
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void namePres(HttpServletRequest request, HttpServletResponse response){
		String preName = request.getParameter("preName");
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			
			try {
				PrescriptionService prescriptionService = new PrescriptionService();

				Iterator iterator = prescriptionService.getPrescriptions(preName,"false").iterator();
				str.append("{articles:[");
				if(iterator.hasNext())
				{
					Prescription prescription = (Prescription)iterator.next();
					str.append("{'id':"+prescription.getId()+",'text':'"+prescription.getName()+"'}");
			
					while(iterator.hasNext()){
						 prescription = (Prescription)iterator.next();
						str.append(",{'id':"+prescription.getId()+",'text':'"+prescription.getName()+"'}");
					}
				}
				str.append("]}");
				out = response.getWriter();
			
			} catch (Exception e) {
				str.append("{articles:[{'id':'','text':'<font color=red>������Ŵ���!</font>'}]}");
			}
		 out.print(str);
		 out.flush();
	}
	
	private void fjPre(HttpServletRequest request, HttpServletResponse response){
		TextService textService = new TextService();
		String fjId = request.getParameter("fjId");
		if(fjId == null || (fjId = fjId.trim()).equals(""))
			return;
		 PrintWriter out = null;
		 String str = "";
			
			try {
				 out = response.getWriter();
				  str = "{articles:"+net.sf.json.JSONArray.fromObject(textService.getPresArticles(fjId)).toString()+"}";
			
			} catch (Exception e) {
				str = "{articles:[{'id':'','text':'<font color=red>�������ĳ��ִ���!</font>'}]}";
			}
		 out.print(str);
		 out.flush();
	}
	
	/**
	 * ��包含药查询
	 * @param request
	 * @param response
	 */
	private void containPre(HttpServletRequest request, HttpServletResponse response){
		String containName = request.getParameter("containName");
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			
			try {
				out = response.getWriter();
				PrescriptionService prescriptionService = new PrescriptionService();
//				getHerbsPrescriptions
				Iterator iterator = prescriptionService.getHerbsPrescriptions(containName,"false").iterator();
				str.append("{articles:[");
//				str.append("{'id':-1,'text':'<font color=red>尚未提供接口</font>'}");
				if(iterator.hasNext())
				{
					Prescription prescription = (Prescription)iterator.next();
					str.append("{'id':'"+prescription.getId()+"','text':'"+prescription.getName()+"'}");
			
					while(iterator.hasNext()){
						 prescription = (Prescription)iterator.next();
						str.append(",{'id':'"+prescription.getId()+"','text':'"+prescription.getName()+"'}");
					}
				}
				str.append("]}");
				 
			} catch (Exception e) {
				str.append("{articles:[{'id':'-1','text':'<font color=red>查询错误!<font>'}]}");
			}
		 out.print(str);
		 out.flush();
	}
	
	
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}